#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#define FOR(i,a,n) for(int i=a,_n(n);i<_n;++i)
#define REP(i,n) FOR(i,0,n)

using namespace std;

vector<int> father,next,cap;

void Dfs(int pos,int pre)
{
	if(next[pos]==-1)
	{
		printf("%d %d\n",pos,pre);
		return ;
	}
	Dfs(next[pos],min(pre,cap[pos]));
}

int main()
{
	int n,p;
	while(cin>>n>>p)
	{
		father.resize(n+1,-1);
		next.resize(n+1,-1);
		cap.resize(n+1,-1);
		while(p--)
		{
			int vs,vt,w;
			scanf("%d%d%d",&vs,&vt,&w);
			father[vt] = vs;
			next[vs] = vt;
			cap[vs] = w;
		}
		int cnt = 0;
		FOR(i,1,n+1) if(father[i]==-1&&next[i]!=-1)
			cnt++;
		printf("%d\n",cnt);
		FOR(i,1,n+1) if(father[i]==-1&&next[i]!=-1)
			printf("%d ",i),Dfs(i,1<<29);
	}
	return 0;
}
